'use strict'
import message from './message'
import REQUEST_KEY from '../config/request'

/**
 * WebSocketUtil
 * 你是一段成熟的代码，要学会自己改bug  ----我是小尾巴
 */

const param = {
  socket: null,
  blcId: ''
}

/**
 * 初始化websocket
 * @param blcId
 * @returns {WebSocket}
 */
export function initWebSocket (blcId = param.blcId) {
  param.blcId = blcId
  const uri = `${REQUEST_KEY.webSocketConfig.protocol} + ${REQUEST_KEY.serviceConfig.host} + ${REQUEST_KEY.serviceConfig.host}/${blcId}`
  param.socket = new WebSocket(uri)
  param.socket.onmessage = e => {
    onMessageWebSocket(e)
  }
  param.socket.onopen = () => {
    onOpenWebSocket()
  }
  param.socket.onerror = () => {
    onErrorWebSocket()
  }
  param.socket.onclose = () => {
    closeWebSocket()
  }
  return param.socket
}

/**
 * 打开websocket连接
 */
export function onOpenWebSocket () {
  // todo
}

/**
 * 接收推送消息
 * @param e
 */
export function onMessageWebSocket (e) {
  // todo
  const data = JSON.parse(e.data)
  method[data.handle](data.jsonData)
}

/**
 * 连接错误
 */
export function onErrorWebSocket () {
  // todo
  initWebSocket()
}

/**
 * 关闭连接
 */
export function closeWebSocket () {
  // todo
  param.socket.close()
}

/**
 * 发送数据
 * @param action
 * @param data
 * @param callback
 */
export function sendMessage (action, data, callback) {
  const message = {
    userData: this.getUserInfo(),
    jsonData: data,
    action,
    handle: callback
  }
  param.socket.send(JSON.stringify(message))
}

/**
 * 处理方法
 * @type {{}}
 */
const method = {
  /**
   * 返回新消息的时候
   * @param data
   */
  newMessage: data => {
    message.notice.success('您有 ' + data.count + ' 条新消息，请及时查看！')
    // 修改数据
  }
}
